package com.liqi.frame.comm.filter;

import cn.hutool.extra.servlet.ServletUtil;
import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.enums.OnlineStatusEnum;
import com.liqi.frame.comm.session.OnlineSession;
import com.liqi.frame.comm.po.User;
import com.liqi.frame.comm.session.OnlineSessionDAO;
import com.liqi.frame.comm.token.TokenUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author liqi on 2020/1/20 0020. liqiwork@qq.com
 */
public class OnlineSessionFilter extends AccessControlFilter {
    /**
     * 强制退出后重定向的地址
     */
    @Value("${shiro.loginUrl}")
    private String loginUrl;
    @Autowired
    EnterpriseCacheSessionDAO enterpriseCacheSessionDAO;
    @Autowired
    OnlineSessionDAO onlineSessionDAO;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {
        Subject subject = getSubject(request, response);

        if (subject == null || subject.getSession() == null) {
            return true;
        }
//        Session session = enterpriseCacheSessionDAO.readSession(subject.getSession().getId());
        Session session = onlineSessionDAO.readSession(subject.getSession().getId());

        String curUrl = WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
        if (curUrl.equalsIgnoreCase(loginUrl)) {
//            当前访问的是登录页
            return true;
        }
        if (session != null && session instanceof OnlineSession) {
            OnlineSession onlineSession = (OnlineSession) session;
            request.setAttribute(Constants.ONLINE_SESSION, onlineSession);
            if (onlineSession.getStatus()!=null && onlineSession.getStatus()== OnlineStatusEnum.OFFLINE.getKey()){
                return false;
            }
            if (onlineSession.getUserId() == null) {
                User user = TokenUtil.getToken();
                if (user!=null) {
                    onlineSession.setUserId(user.getId());
                    onlineSession.setLoginName(user.getFullname());
                    onlineSession.setGroupName(user.getGroupName());
                }
            }
        }
        return true;
    }

    /**
     * 表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；如果返回false表示该拦截器实例已经处理了，将直接返回即可。
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (subject != null) {
            subject.logout();
        }
        saveRequestAndRedirectToLogin(request, response);
        return false;
    }

    /**
     * 跳转到登录页
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        WebUtils.issueRedirect(request, response, loginUrl);
    }
}
